﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace Selenium.Config
{
    [XmlRoot("selenium", Namespace = "",
    IsNullable = false)]
    public class SeleniumConfig
    {
        public const string BrowserChrome = "Chrome";
        public const string BrowserFirefox = "Firefox";
        public const string BrowserIE = "InternetExplorer";

        private const string _xmlFileName = "SeleniumConfig.xml";

        private static readonly XmlSerializer serializer;

        static SeleniumConfig()
        {
            serializer = new XmlSerializer(typeof(SeleniumConfig));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        /// <exception cref="FileNotFoundException"></exception>
        /// <exception cref="IOException"></exception>
        /// <exception cref="InvalidOperationException"></exception>
        public static SeleniumConfig Load()
        {
            
            TextReader reader = new StreamReader(_xmlFileName);

            SeleniumConfig seleniumConfig = (SeleniumConfig)serializer.Deserialize(reader);
            reader.Close();

            return seleniumConfig;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="config"></param>
        /// <exception cref="FileNotFoundException"></exception>
        /// <exception cref="IOException"></exception>
        public static void Save(SeleniumConfig config)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(SeleniumConfig));
            TextWriter writer = new StreamWriter(_xmlFileName);

            serializer.Serialize(writer, config);
            writer.Close();
        }

        [XmlArray("webDrivers")]
        [XmlArrayItem("webDriver")]
        public List<WebDriverConfig> WebDrivers;

        public WebDriverConfig getWebDriver(string browser)
        {
            if (browser == null)
            {
                throw new ArgumentNullException();
            }

            browser = browser.ToLower();
            foreach (WebDriverConfig driver in WebDrivers)
            {
                if (browser.Equals(driver.Browser.ToLower()))
                {
                    return driver;
                }
            }
            return null;
        }

        [XmlElement("option")]
        public OptionConfig Option
        {
            get;
            set;
        }
    }
}
